package setting

import (
	"errors"
	"fmt"
	"github.com/glebarez/sqlite"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/ini.v1"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"moul.io/zapgorm2"
	"strings"
)

var Db *gorm.DB

func initDatabase(config *ini.File) error {
	section := config.Section("database")
	dbType := section.Key("type").MustString("")
	dns := section.Key("dsn").MustString("")
	if dns == "" {
		return errors.New("please specify dns for database")
	}
	if dbType == "" {
		return errors.New("please specify type for database")
	}
	var d gorm.Dialector
	switch strings.ToUpper(dbType) {
	case "MYSQL":
		d = mysql.Open(dns)
	case "SQLITE":
		d = sqlite.Open(dns)
	default:
		return fmt.Errorf("unsupported database type: %s", dbType)
	}
	var err error
	log := zapgorm2.New(zap.L())
	switch zap.L().Level() {
	case zapcore.DebugLevel, zapcore.InfoLevel:
		log.LogLevel = logger.Info
	case zapcore.WarnLevel:
		log.LogLevel = logger.Warn
	case zapcore.ErrorLevel:
		log.LogLevel = logger.Error
	case zapcore.FatalLevel:
		log.LogLevel = logger.Silent
	}
	Db, err = gorm.Open(d, &gorm.Config{
		Logger: log,
	})
	if err != nil {
		return fmt.Errorf("failed to open database connection: %w", err)
	}
	return nil
}
